package com.bp.hearthealth.pulse.lnapps.bp_ui.bp_fragment.bp_tracker.tracker

import android.view.View
import androidx.fragment.app.FragmentTransaction
import com.bp.hearthealth.pulse.lnapps.R
import com.bp.hearthealth.pulse.lnapps.base.BpBaseFragment
import com.bp.hearthealth.pulse.lnapps.databinding.TrackerFragmentBgBinding
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_fragment.bp_tracker.blood_pressure.BloodPressureFragment
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants
import com.bp.hearthealth.pulse.lnapps.bp_utils.DoubleClickListener
import com.gyf.immersionbar.ImmersionBar
import org.koin.androidx.viewmodel.ext.android.viewModel

class BpTrackerFragment : BpBaseFragment<TrackerFragmentBgBinding>() {

    private var bloodPressureFragment: BloodPressureFragment? = null
    private var index = 0

    private val viewModel: BpTrackerViewModel by viewModel()

    override fun loadDataOnce() {
        super.loadDataOnce()
        saveAndSwitch(index)
        viewModel.getCurrentName().observe(this) { index ->
            switchFragment(index)
        }
        binding.ivChange.setOnClickListener(object : DoubleClickListener() {
            override fun onNoDoubleClick(v: View?) {
//                if (index == 2) {
//                    index = -1
//                }
//                saveAndSwitch(index++)
            }
        })
    }

    private fun saveAndSwitch(index: Int) {
        viewModel.saveSelect(index)
        switchFragment(index)
    }

    private fun switchFragment(index: Int) {
        childFragmentManager.beginTransaction().apply {
            hideFragments(this)
            when (index) {
                0 -> {
                    if (bloodPressureFragment == null) {
                        bloodPressureFragment =
                            BloodPressureFragment.newInstance(Constants.BLOOD_PRESSURE_FRAGMENT)
                        add(R.id.tracker_fragment_container, bloodPressureFragment!!)
                    } else {
                        show(bloodPressureFragment!!)
                    }
                }
            }
        }.commit()
    }

    private fun hideFragments(transaction: FragmentTransaction) {
        bloodPressureFragment?.let { transaction.hide(it) }
    }

    override fun initImmersionBar() {
        super.initImmersionBar()
        ImmersionBar.with(this).statusBarDarkFont(true).titleBar(binding.toolbar).init()
    }
}